package com.springcloud.tools.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author fuc
 * @create 2020-08-31
 */
@RestController
public class FileUploadController {

  SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");

  @PostMapping("/upload")
  public Map<String, Object> fileUpload(MultipartFile file, HttpServletRequest req) {
    HashMap<String, Object> result = new HashMap<>(2);
    String originalFilename = file.getOriginalFilename();
    if (originalFilename.endsWith(".pdf")) {
      result.put("status", "error");
      result.put("msg", "文件类型不对");
      return result;
    }
    String format = sdf.format(new Date());
    String realPath = req.getServletContext().getRealPath("/") + format;
    File folder = new File(realPath);
    if (!folder.exists()) {
      folder.mkdirs();
    }
    String newName = UUID.randomUUID().toString() + ".pdf";
    try {
      file.transferTo(new File(folder, newName));
      String url =
          req.getScheme()
              + "://"
              + req.getServerName()
              + ":"
              + req.getServerPort()
              + format
              + newName;
      result.put("status", "success");
      result.put("url", url);
    } catch (IOException e) {
      e.printStackTrace();
      result.put("status", "error");
      result.put("msg", e.getMessage());
    }
    return result;
  }
}
